package cn.dlc.com.config;

import cn.dlc.com.mapper.SysPermissionMapper;
import cn.dlc.com.pojo.SysPermission;
import cn.dlc.com.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;

@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {

    /***
     *
     * @param authentication 这个就是登录之后的用户
     * @param targetUrl 表示的是当前权限的请求地址，比如/order/findAll这些
     * @param targetPermission 权限标志
     * @return
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {

        // 获得loadUserByUsername()方法的结果
        SysUser user = (SysUser)authentication.getPrincipal();
        // 得到当前用户的
        List<SysPermission> permissionList = user.getPermissions();

        // 遍历permissionList
        for(SysPermission sysPermission : permissionList) {

            System.out.println("sysPermission.getPermissionUrl():->" + sysPermission.getPermissionUrl());

            // 如果访问的Url和权限用户符合的话，返回true
            if(targetUrl.equals(sysPermission.getPermissionUrl())) {
                return true;
            }
        }
        return false;

    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
